namespace muduoDotNet
{
    /// <summary>
    /// Timer类，表示定时器
    /// </summary>
    public class Timer : IDisposable
    {
        private readonly Action _callback;
        private TimeStamp _expiration;
        private double _interval;
        private bool _repeat;
        private long _sequence;
        private static long _sNumCreated = 0;
        private bool _disposed;

        internal Timer(Action callback, TimeStamp when, double interval)
        {
            _callback = callback ?? throw new ArgumentNullException(nameof(callback));
            _expiration = when;
            _interval = interval;
            _repeat = interval > 0.0;
            _sequence = Interlocked.Increment(ref _sNumCreated);
            _disposed = false;
        }

        public TimeStamp Expiration => _expiration;
        public bool Repeat => _repeat;
        public long Sequence => _sequence;

        /// <summary>
        /// 获取已创建的定时器数量
        /// </summary>
        public static long NumCreated => _sNumCreated;

        /// <summary>
        /// 运行定时器回调
        /// </summary>
        public void Run()
        {
            if (!_disposed)
            {
                _callback.Invoke();
            }
        }

        /// <summary>
        /// 重新启动定时器
        /// </summary>
        /// <param name="now">当前时间</param>
        public void Restart(TimeStamp now)
        {
            if (!_disposed && _repeat)
            {
                // 计算下一次到期时间
                _expiration = now.AddSeconds(_interval);
            }
            else
            {
                // 一次性定时器，设置为无效
                _expiration = TimeStamp.Invalid;
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                _disposed = true;
            }
        }
    }
}